package com.vayne.concurrent;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author xuerui.zhang
 * @since 2020/4/28 下午3:38
 */
public class CurrentHashMapStepDemo implements Runnable {

    private static ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();

    public static void main(String[] args) throws InterruptedException {
        map.put("score", 0);
        CurrentHashMapStepDemo demo = new CurrentHashMapStepDemo();
        Thread t1 = new Thread(demo);
        Thread t2 = new Thread(demo);
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        System.out.println(map.get("score"));
    }

    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            while (true) {
                Integer oldValue = map.get("score");
                Integer newValue = oldValue + 1;
                boolean flag = map.replace("score", oldValue, newValue);
                if (flag) {
                    break;
                }
            }
        }
    }
}
